package org.easydarwin.activitys;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.google.gson.Gson;

import org.easydarwin.adapter.IndicatorExpandableListAdapter;
import org.easydarwin.beans.Helper;
import org.easydarwin.beans.LoginResult;
import org.easydarwin.beans.Role;
import org.easydarwin.beans.RolesResult;
import org.easydarwin.beans.User;
import org.easydarwin.conf.Constant;
import org.easydarwin.easyrtc.MainActivity;
import org.easydarwin.easyrtc.R;
import org.easydarwin.easyrtc.databinding.ActivityHelperBinding;
import org.easydarwin.network.NetConfig;
import org.easydarwin.network.result.VolleyResult;
import org.easydarwin.util.AccountUtil;
import org.easydarwin.util.AssetsUtil;
import org.easydarwin.util.JsonUtil;
import org.easydarwin.util.LogUtil;
import org.easydarwin.util.PreferenceManager;
import org.easydarwin.util.VolleyUtils;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.List;

public class HelperActivity extends AppCompatActivity implements IndicatorExpandableListAdapter.PhoneClickListener {
    private String TAG = "RemoteHelp";
    private final int getAllRoles = 0x2;
    private MyHandler handler = new MyHandler(this);

    ActivityHelperBinding helpBinding;
    private IndicatorExpandableListAdapter adapter;
    private RolesResult rolesResult;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        helpBinding = DataBindingUtil.setContentView(this , R.layout.activity_helper);

        VolleyUtils.getInstance(this).sendInfo(NetConfig.allRoles, null, new VolleyResult() {
            @Override
            public void success(String result, String method) {
                Message msg = handler.obtainMessage();
                msg.what = getAllRoles;
                LogUtil.i("================================HelperActivity----result = " + result);
                RolesResult res = new Gson().fromJson(result , RolesResult.class);
                msg.obj = res;
                handler.sendMessage(msg);
            }
            @Override
            public void jsonSuccess(JSONObject result, String method) { }
            @Override
            public void failure(String error, String method) { }
        } , Request.Method.GET , true);
    }

    @Override
    public void phone(String phone) {
        if(TextUtils.isEmpty(phone)){
            LogUtil.i("==================phone is null");
            Toast.makeText(this , "phone is null" , Toast.LENGTH_LONG).show();
            return ;
        }
        call(phone);
    }

    /**
     * 调用拨号功能
     * @param phone 电话号码
     */
    private void call(String phone) {
        Intent intent=new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone));
        startActivity(intent);
    }


    private class MyHandler extends Handler {
        private WeakReference< HelperActivity> mAct;
        public MyHandler(HelperActivity act){
            mAct = new WeakReference<HelperActivity>(act);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case getAllRoles:
                    RolesResult res = (RolesResult)msg.obj;
                    mAct.get().showListData(res);
                    break;
            }
        }
    }

    private void showListData(RolesResult result){
        this.rolesResult = result;

        filterMineAccount(rolesResult.getResponse());

        initExpandList(rolesResult.getResponse());
    }

    private void filterMineAccount(List<Role> roles){
        if(null == roles || roles.size() == 0){return ;}
        String mineAccount = PreferenceManager.getInstance().getAccount();
        String roleCode = PreferenceManager.getInstance().getRole("");
        for(int i = 0 ; i < roles.size() ; i++){
            if(roleCode.equals(roles.get(i).getCode())){
                roles.remove(i);
            }
            if(roles.get(i).getUsers().size() == 0){
                roles.remove(i);
            }

            for(int j = 0 ; j < roles.get(i).getUsers().size() ; j ++){
                User user = roles.get(i).getUsers().get(j);
                if(mineAccount.equals(user.getAccount())){
                    LogUtil.i("=========================remove " + user.getNickname() +"--account = " + user.getAccount());
                    roles.get(i).getUsers().remove(j);
                    j--;
                }
            }
        }

    }


    private void initExpandList(List<Role> roles){
        if(null == adapter){
            adapter = new IndicatorExpandableListAdapter(this, roles);
            adapter.setListener(this);
            helpBinding.expandList.setAdapter(adapter);
            // 清除默认的 Indicator
            helpBinding.expandList.setGroupIndicator(null);
            //  设置分组项的点击监听事件
            helpBinding.expandList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
                @Override
                public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                    Log.d(TAG, "onGroupClick: groupPosition:" + groupPosition + ", id:" + id);
                    boolean groupExpanded = parent.isGroupExpanded(groupPosition);
                    adapter.setIndicatorState(groupPosition, groupExpanded);
                    // 请务必返回 false，否则分组不会展开
                    return false;
                }
            });

            //  设置子选项点击监听事件
            helpBinding.expandList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                @Override
                public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
//                Toast.makeText(HelperActivity.this, Constant.FIGURES[groupPosition][childPosition], Toast.LENGTH_SHORT).show();
//                Toast.makeText(HelperActivity.this, rolesResult.getResponse().get(groupPosition).getUsers().get(childPosition).getNickname() , Toast.LENGTH_SHORT).show();
                    User user = rolesResult.getResponse().get(groupPosition).getUsers().get(childPosition);
                    if(user.isOnline()){
                        gotoVideoActivity(user);
                    }
                    return true;
                }
            });
        }else{
            adapter.notifyDataSetChanged();
        }
    }


    private void gotoVideoActivity(User user){
        Intent intent = new Intent(this , MainActivity.class);
        PreferenceManager.getInstance().setFriendAccount(user.getAccount());
        String mineAccount = PreferenceManager.getInstance().getAccount();
        String pushId;
        if(AccountUtil.isCustom("")){
            pushId = mineAccount + "_" + user.getAccount();
        }else{
            pushId = user.getAccount() +"_" + mineAccount;
        }
        LogUtil.i("=====================HelpActivity --- pushId = " + pushId);
        PreferenceManager.getInstance().setPushID(pushId);
        startActivity(intent);
    }
}
